#include "AFBitmapConverter.h"

/* Converts RGB values to aRGB values */
#define aRGB(a,r,g,b) ((unsigned int)(a<<24)|(r<<16)|(g<<8)|(b))

BITMAPFILEHEADER bmpFileHeader;
BITMAPINFOHEADER bmpInfoHeader;

SPRITEIMAGE ReadInBitmap(char* filename)
{
	/* The image of the sprite that is read in and created */
	SPRITEIMAGE spriteImage;
	
	//char* filename = "bitmaps/24bitBitmapTest.bmp";
	//char* filename = "bitmaps/sampletext.bmp";
	//char* filename = "bitmaps/solidgold.bmp";
	//char* filename = "bitmaps/BitmapTest.bmp";
	//char* filename = "bitmaps/ryu.bmp";
	
	FILE * filepointer; 
	
	filepointer = fopen(filename, "rb");

	if(filepointer)
	{
		/* Read in the file header of the bitmap file */
		fread(&bmpFileHeader, sizeof(bmpFileHeader), 1, filepointer);
		/* Read in the info header of the bmp file */
		fread(&bmpInfoHeader, sizeof(bmpInfoHeader), 1, filepointer);

		/* Storing the width and height value of the image */
		spriteImage.width = bmpInfoHeader.biWidth;
		spriteImage.height = bmpInfoHeader.biHeight;

		/* If we have a 24-bit Bitmap file */
		if(bmpInfoHeader.biBitCount == 24)
		{
			/* Start Reading the Bitmap */
			int heightIndex, widthIndex = 0; /* Indexes */
			PIXEL image; /* Stores RGB values */
			int color = 0; /* Stores aRGB values */

			/* Create a buffer for the image that is the size of the image */
			dpPixel* imageBuffer = malloc(bmpInfoHeader.biWidth * bmpInfoHeader.biHeight * sizeof(dpPixel));

			for(heightIndex = bmpInfoHeader.biHeight; heightIndex > 0; --heightIndex)
			{
				for(widthIndex = 0; widthIndex < bmpInfoHeader.biWidth; ++widthIndex)
				{
					/* Read in each color value of a pixel from a bitmap image */
					fread(&image.blue, sizeof(BYTE), 1, filepointer);
					fread(&image.green, sizeof(BYTE), 1, filepointer);
					fread(&image.red, sizeof(BYTE), 1, filepointer);
					//fseek(filepointer, sizeof(BYTE), SEEK_CUR); /* Padding */

					/* Create a aRGB value from the RGB values */
					color = aRGB(0xFF, image.red, image.green, image.blue);

					/* Draw the color onto a buffer */
					//if(color != 0xFF408000)
					//{
					//*(imageBuffer +  widthIndex + (heightIndex - 1) * dpScreenWidth) = color;
					*(imageBuffer +  widthIndex + (heightIndex - 1) * spriteImage.width) = color;
					//}
				}
			}

			spriteImage.image = imageBuffer;
		}
	}
	fclose(filepointer);
	return spriteImage;
}

/* Draws a bitmap from the top of the screen */
void DrawBitmap(dpPixel* buffer, SPRITEIMAGE spriteImage)
{
	/* x and y can be passed in values for the coordinates*/
  int x = 0;
  int y = 0;
  for(y=0;y<spriteImage.height && y<dpScreenHeight;++y)
  {
	  for(x=0;x<(spriteImage.width) && x<dpScreenWidth;++x)
    {
		if(*(spriteImage.image + x + y * spriteImage.width) != 0xFFFF00DE) //PINK SCREEN, GREEN SCREEN = 0xFF408000
		*(buffer + x + y  * dpScreenWidth) = *(spriteImage.image + x + y * spriteImage.width);
    }
  }
}